<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: StsWorker.php
 * Date: 2017/1/11
 * Time: 23:59
 */

namespace app\library\aliyun\sts;

use app\library\CommonConfig;

class StsWorker
{
    private $policy;

    public function __construct($user_id)
    {
        $this->setPlicy($user_id);
    }

    /**
     * @return bool|mixed
     * @throws ClientException
     */
    public function getToken()
    {
        // 角色资源描述符，在RAM的控制台的资源详情页上可以获取
        $iClientProfile = DefaultProfile::getProfile(CommonConfig::STS_REGION, CommonConfig::STS_ACCESSKEYID, CommonConfig::STS_ACCESSKEYSECRET);
        $client = new DefaultAcsClient($iClientProfile);
        $request = new AssumeRoleRequest();
        $request->setRoleSessionName(CommonConfig::STS_ROLE_SESSION_NAME);
        $request->setRoleArn(CommonConfig::STS_ROLEARN);
        $request->setPolicy($this->policy);
        $request->setDurationSeconds(1000);
        $response = $client->doAction($request);
        if ($response->getStatus() == 200) {
            return json_decode($response->getBody(), true);
        } else {
            return false;
        }
    }

    public function setPlicy($userid)
    {
        //以用户id创建文件夹，并且只有此文件夹下的权限
        $resourceList = sprintf("acs:oss:*:*:manshe-app");
        $resourceWrite = sprintf("acs:oss:*:*:%s/%s/*", CommonConfig::OSS_BUCKET, $userid);
        $policy = [
            'Statement' => [
                [
                    "Action" => ["oss:*"],
                    "Effect" => "Allow",
                    "Resource" => [
                        $resourceList,
                        $resourceWrite
                    ],
                ]
            ],
            "Version" => "1",
        ];
        $this->policy = json_encode($policy);
    }

    public function getPolicy()
    {
        return $this->policy;
    }
}
